﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace gzdanny.web_lib
{
    /// <summary>
    /// 从指定的URL获取HtmlDoc页面，并通过正则表达式RegExp对页面页面内容数据抽取，通过MatchCollection Matchs返回。
    /// </summary>
    class WebGrabber
    {
        private HttpRequest hrq = new HttpRequest();

        public string URL { get { return hrq.RequestUriString; } set { hrq.RequestUriString = value; } }
        public string Referer = string.Empty;
        public string PostData = string.Empty;
        public string CharSet { get { return hrq.CharacterSet; } set { hrq.CharacterSet = value; } }
        public string HtmlDoc { get { return hrq.HtmlDocument; } }

        public string RegExp { get { return rg.ToString(); } set { rg = new Regex(value); } }
        private Regex rg = new Regex(string.Empty);
        public MatchCollection Matchs { get { return rg.Matches(HtmlDoc); } }

        public WebGrabber(string _CharSet)
        {
            this.CharSet = _CharSet;
        }
        public WebGrabber():this("UTF-8"){}

        public bool Open(string url, string referer, string postdata)
        {
            //如果需要自动使用上次页面地址作为引用页面，可以在引用页参数输入一个空字符
            if (referer.Length < 2) { Referer = URL; } else { Referer = referer; }
            URL = url;
            PostData = postdata;
            return hrq.OpenRequest(URL, Referer, PostData);
        }
        public bool Open(string url, string referer)
        {
            //如果需要自动使用上次页面地址作为引用页面，可以在引用页参数输入一个空字符
            if (referer.Length < 2) { Referer = URL; } else { Referer = referer; }
            URL = url;
            PostData = string.Empty;
            return hrq.OpenRequest(URL, Referer);
        }
        public bool Open(string url)
        {
            URL = url;
            Referer = string.Empty;
            PostData = string.Empty;
            return hrq.OpenRequest(URL);
        }

        internal bool Open()
        {
            Referer = string.Empty;
            PostData = string.Empty;
            return hrq.OpenRequest(URL);
        }
    }
}
